﻿using DotNet.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace XNWebService
{
    /// <summary>
    /// 敏感词检测
    /// </summary>
    public class SensitiveWord
    {
        public static Regex reg_word = null;

        /// <summary>
        /// 读取敏感词
        /// </summary>
        /// <returns></returns>
        private static string[] GetDataBaseBlockWords()
        {
            JsonDataFile<Dictionary<string, string>> d = new JsonDataFile<Dictionary<string, string>>("SensitiveWord.json");
            //List<string> dataBaseWords = new List<string>();
            //string[] rets = dataBaseWords.ToArray();
            string[] rets = d.Data["KeyWorld"].Split('|');
            return rets;
        }

        /// <summary>
        /// 敏感词组织成正则
        /// </summary>
        /// <returns></returns>
        private static string GetPattern()
        {
            StringBuilder patt = new StringBuilder();
            foreach (string word in GetDataBaseBlockWords())
            {
                if (word.Length == 0)
                    continue;

                patt.AppendFormat("|{0}", word);
            }

            if (patt.Length > 0)
            {
                patt.Remove(0, 1);
            }
            return patt.ToString();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private static Regex GetRegex()
        {
            if (reg_word == null)
            {
                reg_word = new Regex(GetPattern(), RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
            }
            return reg_word;
        }

        private static bool HasBlockWords(string raw)
        {
            return GetRegex().Match(raw).Success;
        }

        private static string WordsFilter(string raw)
        {
            string ret = GetRegex().Replace(raw, "***");
            return ret;
        }

        /// <summary>
        /// 刷新正则
        /// </summary>
        /// <returns></returns>
        public static Regex ReSetRegex()
        {
            reg_word = new Regex(GetPattern(), RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
            return reg_word;
        }

        /// <summary>
        /// 检测敏感词
        /// </summary>
        /// <param name="raw"></param>
        /// <returns></returns>
        public static bool CheckWords(string raw)
        {
            return HasBlockWords(raw);
        }

        /// <summary>
        /// 替换敏感词
        /// </summary>
        /// <param name="raw"></param>
        /// <returns></returns>
        public static string ConvertToFilterWords(string raw)
        {
            string ret = raw;
            if (HasBlockWords(raw))
            {
                ret = WordsFilter(raw);
            }
            return ret;
        }


    }
}
